// 用户信息
var username = '';
var defaultName = "匿名小白";
var pass = 'none';

// window.onload = function () {
pass = localStorage.getItem("pass") || pass;
document.getElementById("mima").value = pass;
mima({ value: pass })
var name_ = localStorage.getItem("userLoNmae") || defaultName;
document.getElementById("userDIY").value = name_;
document.getElementById("nowName").innerHTML = name_;
document.getElementById("nowName2").innerHTML = name_;
username = name_;

document.getElementById('m').focus();

setInterval(() => {
  closeLempchat();
}, 1000 * 60 * 5);
// }

var socket = io('', {
  // Send auth token on connection, you will need to DI the Auth service above
  path: '/socket.io',
  transports: ['websocket', 'wwjwwj'],
  secure: true,
  query: {
    id: pass
  },
});

function getCurrentTime(time = null) {
  var date = new Date(time); //当前时间
  var month = zeroFill(date.getMonth() + 1); //月
  var day = zeroFill(date.getDate()); //日
  var hour = zeroFill(date.getHours()); //时
  var minute = zeroFill(date.getMinutes()); //分
  var second = zeroFill(date.getSeconds()); //秒
  //当前时间
  var curTime = "time: " + month + "-" + day +
    " " + hour + ":" + minute + ":" + second;
  return curTime;
}

/*
 * 补零
 */
function zeroFill(i) {
  if (i >= 0 && i <= 9) {
    return "0" + i;
  } else {
    return i;
  }
}


// 监听用户增减
socket.on('renshu', (renshu) => {
  // 添加一条系统消息
  document.getElementById("RS").innerText = "当前在线人数: " + renshu;
})

// 发送事件
let isOneSendMe = true;
function SendM(obj) {
  let m = obj || document.getElementById("m");
  if (m.value != "") {
    let message = { username: username, msg: m.value, time: new Date().getTime() }
    socket.emit('sendMessage', message);
    saveMessage(message);
    m.value = "";
    // 发送邮箱
    if (pass != '18820651349' && isOneSendMe) { fetch('/nodemailder').then(() => { }) }
    isOneSendMe = false;
  }
  obj && obj.id && document.getElementById('m').focus();
}

// 图片发送事件
document.getElementById("inputImg").onclick = function (e) {
  e.target.value = "";
}

function sendImg(input) {
  let file = input.files[0];
  let imgTs = document.getElementById("imgTs");
  // let size = file.size / 1024;
  // if (size < 750) {
  let reader = new FileReader();
  imgTs.style.visibility = "visible";
  imgTs.innerText = "读取中...";
  reader.readAsDataURL(file);
  // 读取完后，输出
  reader.onload = function () {
    imgTs.innerText = "尝试发送中...";
    socket.emit('sendimage', {
      username: username,
      img: reader.result,
      time: new Date().getTime()
    });
    imgTs.style.visibility = "hidden";
  }
  // } else {
  //   imgTs.innerText = "图片大于750kb，不予发送";
  //   imgTs.style.visibility = "visible";
  //   setTimeout(function () {
  //     imgTs.style.visibility = "hidden";
  //   }, 2600);
  // }
  input.value = "";
}


const messages = document.getElementById('messages');
// 捕获事件
socket.on('sendMessage', addMessage);
function addMessage(data, issave = true) {
  saveMessage(data, issave);
  let html = '';
  html = `<li class="${data.username == username ? 'mySelf' : 'qiTa'}">
    <h4>${data.username}</h4> <br>
    <pre onclick="copyText(this)">${to_link(data.msg)} </pre>
  </li>`
  messages.insertAdjacentHTML('beforeend', html);
  setTimeout(smoothscroll, 100);
}

// 捕获图片事件
socket.on('sendimage', addImg);
function addImg(data) {
  let html = '';
  html = `
  <li class="${data.username == username ? 'mySelf' : 'qiTa'}">
    <h4>${data.username}</h4><br />
    <img src="${data.img}" onclick="openYLK(this)" />
  </li>`
  messages.insertAdjacentHTML('beforeend', html);
  setTimeout(smoothscroll, 200);
}

function smoothscroll() {
  const currentScroll = messages.scrollTop; // 已经被卷掉的高度
  const clientHeight = messages.offsetHeight; // 容器高度
  const scrollHeight = messages.scrollHeight; // 内容总高度
  if (scrollHeight - 10 > currentScroll + clientHeight) {
    window.requestAnimationFrame(smoothscroll);
    messages.scrollTo(0, currentScroll + (scrollHeight - currentScroll - clientHeight) / 2);
  }
}


// 键盘事件绑定
document.onkeydown = function (event) {
  var e = event || window.event || arguments.callee.caller.arguments[0];
  if (e && e.ctrlKey && e.key === 'Enter') { // enter 键
    //要做的事情C
    SendM();
  } else if (e && e.keyCode == 113) {
    qKong();
  }
}

// 清空
function qKong() {
  document.getElementById('m').value = '';
  document.getElementById('m').focus();
}


// js 正则表达式来检查是否是链接
function to_link(txtContent) {
  var check_www = 'w{3}' + '[^\\s]*';
  var check_http = '(https|http|ftp|rtsp|mms)://' + '[^\\s]*';
  var strRegex = check_www + '|' + check_http;
  var httpReg = new RegExp(strRegex, 'gi');
  formatTxtContent = txtContent.replace(httpReg, function (httpText) {
    return `<a href="javascript:void(0);" onclick="openNewUrl(this, '${httpText.search('http') < 0 && httpText.search('HTTP') < 0 ? 'http://' + httpText : httpText}')" >${httpText}</a>`
  });
  return formatTxtContent;
}
function openNewUrl(event, url) {
  console.log(`event`, event);
  window.open(url)
}

// 改名操作
function tbuName() {
  let name = document.getElementById("userDIY").value || defaultName;
  document.getElementById("nowName").innerText = name;
  document.getElementById("nowName2").innerText = name;
  username = name;
}
function okCOls() {
  document.getElementById("userData").style.top = "-100%";
  if (document.getElementById("loname").checked == true) {
    localStorage.setItem("userLoNmae", document.getElementById("userDIY").value);
  } else {
    localStorage.removeItem("userLoNmae");
  }
  location.reload()
}
function okOpen() {
  document.getElementById("userData").style.top = "0";
  document.getElementById("userDIY").focus();
}

/* 按钮快速发送消息 start */
// 修改密码，让快捷发送信息按钮显示处理
function addjiaijiejian() {
  fetch(`/get?target=kuaijiejian`, {}).then(response => {
    if (response.status >= 200 && response.status < 300) { // 判断请求是否成功
      return response.json() // 得到 JSON 对象
    } else {
      throw new Error(response.statusText);
    }
  }).then(json => {
    let data = json || [];
    let html = '';
    document.getElementById('anniu').innerHTML = html;
    data.forEach(element => {
      html += `<button type="button" onclick="sendMe('${element.message}')">${element.tag}</button>`
    });
    document.getElementById('anniu').insertAdjacentHTML('beforeend', html);
  }).catch(err => {
    console.log('Request Failed', err)
  });
}
function mima(p) {
  let name = p || document.getElementById("mima");
  if (name.value.trim() == '18820651349') {
    document.getElementById("zankai").style.visibility = "visible";
    document.getElementById("closeButton").style.visibility = "visible";
    addjiaijiejian();
  } else {
    document.getElementById("zankai").style.visibility = "hidden";
    document.getElementById("anniu").style.visibility = "hidden"
    document.getElementById("closeButton").style.visibility = "hidden"
  }
  localStorage.setItem("pass", name.value.trim());
  pass = name.value.trim()
}
// 点击按钮，发送信息
function sendMe(str = '') {
  SendM({ value: str });
  return true;
}
// 展开功能按钮
document.getElementById("zankai").addEventListener('click', () => {
  let flag = document.getElementById("anniu").style.visibility;
  if (flag == "visible") {
    document.getElementById("anniu").style.visibility = "hidden"
  } else if (flag == "hidden" || flag == "") {
    document.getElementById("anniu").style.visibility = "visible"
  }
})

let renshu_ = 0;
// 监听用户增减
socket.on('renshu', (renshu) => {
  if (renshu_ < renshu) { playAudio(lai); }
  else { playAudio(zou); }
  renshu_ = renshu;
})

// 判断网页是否和用户产生交互，必要audio媒体的play()方法异常。
var hasUserInteracted = false;
document.body.addEventListener('click', function () {
  hasUserInteracted = true;
});

// 音源素材：https://sc.chinaz.com/tag_yinxiao/tishiyin.html
// 创建一个新的audio元素
var audioElement = document.createElement('audio');
// 设置audio元素的属性
audioElement.preload = 'auto'; // 预加载音频
audioElement.controls = false; // 显示默认控件
// 添加到文档中（例如，添加到body元素的末尾）
document.body.appendChild(audioElement);
// 播放音频的函数
function playAudio(url) {
  if (!hasUserInteracted) return;
  try {
    audioElement.src = url; // 设置音频源
    audioElement.play().catch(function (error) {
      console.log('播放媒体失败:', error);
    });; // 播放音频
  } catch (error) {
    console.log("打开音乐异常")
  }
}
// 示例：播放初始音频
var lai = 'https://downsc.chinaz.net/Files/DownLoad/sound1/202403/xm2569.mp3';
var zou = 'https://downsc.chinaz.net/Files/DownLoad/sound1/202306/y1900.mp3'

// 对方来信则提示
socket.on('sendMessage', function (data) {
  if (data.username != username) playAudio(lai);
});

// 发送关闭其他用户
function myClose() {
  socket.emit('closeUsers', { username: username, msg: 'closeUsers', });
}
// 收到关闭其他用户
socket.on('closeUsers', function (data) { closeLempchat(); });
function closeLempchat() {
  if (pass != '18820651349') { localStorage.clear(); window.location = '/close.html'; };
}
/* 按钮快速发送消息 end */

/* 保留短时间内的聊天记录 start */
function saveMessage(data, issave) {
  try {
    issave && localStorage.setItem(new Date().getTime(), JSON.stringify(data))
  } catch (error) { }
}
function initMessage() {
  if (localStorage.length < 1) return;
  // 获取 localStorage 中所有的键
  var keys = Object.keys(localStorage);
  keys = keys.sort();
  // 遍历所有键，并获取对应的值
  keys.forEach(key => {
    try {
      let k = Number(key);
      if (!k) return;
      let vv = 1000 * 60 * 3;
      if (k + vv < new Date().getTime()) { localStorage.removeItem(key) }
      else { addMessage(JSON.parse(localStorage.getItem(key)), false) }
    } catch (error) { }
  });
}
initMessage()
/* 保留短时间内的聊天记录 end */